<template>
	<!-- 海报(想让海报显示隐藏要用hidden，v-if关闭后没办法在完整的出来海报) 保存海报按钮和关闭按钮 在html代码中写出来 绑定点击方法然后透明 再用canvas 覆盖 -->
	<!-- 海报(想让海报显示隐藏要用hidden，v-if关闭后没办法在完整的出来海报) 保存海报按钮和关闭按钮 在html代码中写出来 绑定点击方法然后透明 再用canvas 覆盖 -->
	<view class="canvas_box" :hidden="canvasFlag">
		<view class="canvas_box_mask"></view><!-- 遮罩 -->
		<!-- 关闭 -->
		
        <view class="canvasBox" v-if="canvasImg">
            <view class="canvasItem">
                <image mode="widthFix" style="width:100%;height:auto" :src="canvasImg"></image>
            </view>
			<view class="u-flex u-flex-between">
            <view class="u-flex-6 u-padding-20">
				<u-button type="success" icon="download"  @tap="onSaveImg" text="保存海报"></u-button>
			</view>
			<view class="u-flex-6 u-padding-20">
				<u-button type="warning" icon="close"  @tap="canvasCancelEvn" text="关闭"></u-button>
			</view>
			</view>
        </view>
	</view>

</template>

<script>
	import _canvas from '@/uni_modules/fan-canvas/canvasUtils';// 加载万能绘制方法
	import { saveTempFilePathImg } from '@/uni_modules/fan-canvas/plugins/utils';// 需要保存图片可以引用此文件
	import uQRCode from '@/uni_modules/Sansnn-uQRCode/js_sdk/u-qrcode';
	import { pathToBase64 } from '@/plugins/image-tools.js'
	export default {
		data() {
			return {

			}
		},
		props: {
			canvasFlag: {
				type: Boolean,
				default: true,
			},
			posterObj: {
				type: Object,
				default: {
					url: '', //商品主图
					icon: 'https://img0.zuipin.cn/mp_zuipin/poster/hch-hyj.png', //会员价图标
					title: "", //标题
					discountPrice: "", //折后价格
					orignPrice: "", //原价
					code: '', //小程序码
				}
			}
		},
    data() {
        return {
            // #ifndef H5
            goodsImg:'https://img02.163.gg/img/96/66/75/966675-ieuskndmvo.jpg!YM0000',
            // goodsImg:'https://api.yichengshi.cn/minImage/sx2/sx2IndexHeadBg.jpg',
            // #endif
            // #ifdef H5
            goodsImg:'https://img02.163.gg/img/96/66/75/966675-ieuskndmvo.jpg!YM0000',
            // #endif
            rectangleImg:'', //矩形
            rectangleBorderImg:'', //矩形+边框
            circularImg:'',  //圆形头像
            coverImg:'',     //不变形图片-最短边显示完整
            buttonImg:'',    //按钮
            canvasImg:'',    //生成的海报图片
            qrcodeImg:'',    //二维码本地图片
            content:'canvas万能制作方法，新手简单入手，易学，一天掌握canvas制作。绘制矩形方法、加载图片方法、绘制圆形头像方法、绘制图片cover不变形、文本自定义换行超出省略、绘制圆角按钮等方法。组合起来用，基本海报都能绘制。',   //内容
			textImg:'',      //文本超出省略
			content2:"The universal canvas making method is easy for beginners to learn and master canvas making in one day.中英文一起绘制文字也不影响换行，英文换行不会截断单词",
			textEnImg:'',    //英文
		}
    },
	
		methods: {
			// 海报
        async createGoodsPoster() {
			var that = this;
            if(this.canvasImg){
            	return
            }
			
			console.log('qrcodeImg',this.qrcodeImg)
        	
        	uni.showLoading({
        		title: '海报生成中'
        	});
        	const cvsW = 600;
        	const cvsH = 730;
            const goodsH = 400;
        	const logo_w = 100;
            const margin = 30;
        	let family = " 'PingFang SC',tahoma,arial,'helvetica neue','hiragino sans gb','microsoft yahei',sans-serif";
        	let ctx = uni.createCanvasContext('firstCanvas');
            // 绘制矩形
        	_canvas.fillRoundRect(ctx,0,0,cvsW,cvsH,20,"#ffffff");
            // 同步加载图片
        	var logo = await _canvas.getImageInfo(this.posterObj.url);//this.posterObj.url
			//var avatar_url = pathToBase64(this.posterObj.avatar_url)
			//console.log('logo',avatar_url)
        	if(logo.path){
                // save+clip+restore:防止图片超出边框显示--相当于overflow: hidden;
                ctx.save();
                ctx.clip(); //剪切--不允许超出矩形框
                // 绘制商品图片
                _canvas.drawImgCover(ctx, logo, 0, 0, cvsW, goodsH);
                ctx.restore();
                
                // 价格符号
                ctx.setFillStyle('#ff0036')
                ctx.font = "24px" + family
                ctx.fillText(that.posterObj.priceymbol, margin-5, 450)
                // 价格
                ctx.font = "40px" + family
                ctx.fillText(that.posterObj.discountPrice, 50, 450)
                
                // 绘制圆角按钮
                // 参数：cxt、背景颜色、x坐标、y坐标、宽度、高度、圆角、文字、文字颜色、文字位置
				if (that.posterObj.orignPrice>0){
					ctx.font = '22px' + family
					_canvas.drawButton(ctx, 'red', 165, 418, 170, 32, 16, '市场价:'+that.posterObj.priceymbol+' '+that.posterObj.orignPrice, '#ffffff', 'center')
				}

                // 简介-多行文字
        		ctx.setFillStyle('#666666')
                ctx.textAlign = 'left';
        		var options = {
        			font:"normal 26px"+family,     //设置字体
        			ctx:ctx,
        			word:that.posterObj.goodsdescription,      //文本
        			maxWidth:540,           //最大宽度
        			maxLine:2,              //最大行数--超出省略
        			x:margin,               //x坐标
        			y:450,                  //y坐标
        			l_h:40                  //行高
        		}
                // 文本自定义换行
        		_canvas.dealWords(options)
                // 绘制圆形头像
                _canvas.drawCircular(ctx, logo.path, margin, goodsH+margin+160, logo_w, logo_w);
                // 名称
                ctx.setFillStyle('#000000')
                ctx.font = "bold 26px" + family
                ctx.fillText(that.posterObj.nickname, logo_w+margin+10, goodsH+margin+195)
                // 简介
                ctx.setFillStyle('#999999')
                ctx.font = "normal 22px" + family
                ctx.fillText(that.posterObj.webdesc, logo_w+margin+10, goodsH+margin+235)
				
			const ctxq = uni.createCanvasContext('qrcode',this);
			const uqrcode = new uQRCode(
			  {
				text: that.posterObj.qrcodetxt,//二维码参数
				size: 300
			  },
			  ctxq
			);
			uqrcode.make();
			uqrcode.draw().then(()=>{
				uni.canvasToTempFilePath({
				    width: 600,
				    height: 600,
				    canvasId: 'qrcode',
				    success(res) {
				        // 二维码本地图
				        that.qrcodeImg = res.tempFilePath
				        //console.log(res.tempFilePath,'createQrcode')
						// 绘制二维码
						ctx.drawImage(that.qrcodeImg, cvsW-margin-130, goodsH+margin+80+60, 130, 130);
						// 绘制图片
						ctx.draw(false, function() {
							uni.canvasToTempFilePath({
								width: cvsW,
								height: cvsH,
								canvasId: 'firstCanvas',
								success(res) {
									uni.hideLoading();
									that.canvasImg = res.tempFilePath
								}
							},that)
						}, 500)
				    }
				},that)
			})
				
				

				
        	}else{
        		uni.hideLoading();
				this.canvasFlag = true;
        		uni.showToast({
        			title: '海报制作失败',
        			icon: 'none'
        		});
        	}
        },
        // 保存图片
        async onSaveImg() {
        	let imgUrl = "";
        	if(this.canvasImg){
        		imgUrl = await this.canvasImg;
                saveTempFilePathImg(imgUrl)
        	}
        },
		// 创建二维码
		async createQrcode(){
			
		    var that = this
			const ctx = uni.createCanvasContext('qrcode',this);
			const uqrcode = new uQRCode(
			  {
				text: 'https://www.baidu.com',//二维码参数
				size: 300
			  },
			  ctx
			);
			uqrcode.make();
			uqrcode.draw().then(()=>{
				uni.canvasToTempFilePath({
				    width: 600,
				    height: 600,
				    canvasId: 'qrcode',
				    success(res) {
				        // 二维码本地图
				         that.qrcodeImg = res.tempFilePath
				        console.log(res.tempFilePath,'createQrcode')
				    }
				},that)
			})
		},
			// 取消海报
			canvasCancelEvn() {
				console.log('关闭海报')
				this.$emit('cancel', true)
			}
		}
	}
</script>

<style lang="scss">
	.content {
		text-align: center;
		height: 100%;
	}

	.canvas_box {
		.canvasBox{
			position: fixed;
			top:0px;left:0px;
			z-index: 1005;
			.canvasItem{
				width: 100vw;
				height: calc(100vh - 150px);
			}
		}
		.canvas_box_mask {
			width: 100%;
			height: 100%;
			position: fixed;
			top: 0;
			right: 0;
			bottom: 0;
			left: 0;
			background: rgba(255, 255, 255, 1);
			z-index: 1000;
		}

	}
</style>